<?php

Class IndexController Extends Controller {
	
	private function search_results($keywords,$dict='en-kh'){
				
		//code here	
		//Use SQL query in this function
		
		//Pre-defined variables
		$returned_result = array();
		$where = "";//construct where query
		//split out the keyword than sent from from.		
		$keywords = preg_split('/[\s]/', $keywords); // spaces -> =explod(' ',$keyword) , this return an array
		$total_keywords = count($keywords);
		foreach ($keywords as $key=>$keyword){
			//%% search from both side = left and right
			$where .= "`word` LIKE '%$keyword%'";
			if($key != ($total_keywords-1)){
				$where .=" AND ";
			}
		}
		switch ($dict) {
			case 'en-kh':
				$db = $this->hook->db;				
				$sql = "SELECT *  FROM `en-kh` WHERE $where limit 1" ;
	            $stmt = $db->prepare($sql);
	            $stmt->bindParam(':id', $id);
	            $stmt->execute();
	            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
				//How many results that ruturned
				$results_num = sizeof($results);
				if($results_num === 0) {
					echo false;
				} else {
					 foreach ($results as $row){
						$returned_results[] = array(
												'word'=>$row['word'],
												'khmer'=>$row['khmer']
												);
					 
					 }
					
				break;			
			}
			default:
				$returned_results[] = array();
				break;
			
		}
		
			return $returned_results;
	}
	public function index() {
			/*** set a template variable ***/
			$data['title'] = 'ពហុវចនានុក្រម';
			if (isset($_GET["keywords"])){
				
				$keywords = htmlentities(trim($_GET["keywords"]));
				
				$dict = $_GET['selectDict'];
				//Minimum the search term
				$errors = array();
				
				//$search_results = $this->search_results($keywords, $dict);
				$db = $this->hook->db;
				// select a collection  
				$collection = $db->english_khmer;					
				 // retrieve existing document 
				 $criteria = array(
				    				'WORD' => $keywords,
				 					);
				$doc = $collection->findOne($criteria);		
				
				if(empty($keywords)){
					$errors[] = "please enter the search term";
					
				} else if(strlen($keywords)==""){
					$errors[] = "Your search team must be one or more charactor";
				} else if($doc===false){
					$errors[] = "Your search for'.$keywords.' returnend no results";
				}
				
				if(empty($errors)){								
					$data['doc'] =$doc;
				}
				$data['errors'] =$errors;
		}
		
		$this->hook->template->data = $data;
		/*** load the index template ***/
	    $this->hook->template->call('index');
	}

}

?>
